package com.zx.cloud.security.utils;

import com.google.gson.Gson;

import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信工具类
 * @author zhaoxuan
 * @date 2022-04-07 14:29
 **/
@Slf4j
@Data
public class WxUtils implements Serializable {

    private static final long serialVersionUID = -2102666940648296809L;
    /**
     * 获取accessToken的url
     */
    private String accessTokenUrl;
    /**
     * 发送模板消息的url
     */
    private String sendContentUrl;
    /**
     * 微信appid
     */
    private String appid;
    /**
     * 微信appsecret
     */
    private String appsecret;
    /**
     * 模板消息id
     */
    private String templateid;


    public WxUtils(String accessTokenUrl,
                   String sendContentUrl,
                   String appid,
                   String appsecret,
                   String templateid) {
        this.accessTokenUrl = accessTokenUrl;
        this.sendContentUrl = sendContentUrl;
        this.appid = appid;
        this.appsecret = appsecret;
        this.templateid = templateid;
    }

    /**
     * 获取accessToken
     * @return
     */
    public String getAccessToken() {
        Map<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("access_token", "error");
        resultMap.put("expires_in", "0");
        try {
            String getAtUrl = accessTokenUrl + "&appid=" + appid + "&secret=" + appsecret;
            String resultAtInfo = HttpUtil.get(getAtUrl);
            if (resultAtInfo != null) {
                //如果不包含 是正确的结果
                if (!resultAtInfo.contains("errcode")) {
                    Map map = new Gson().fromJson(resultAtInfo, Map.class);
                    log.warn("resultAtInfo {} access_token map {}",resultAtInfo,new Gson().toJson(map));
                    String accessToken = map.get("access_token").toString();
                    String acDuration = map.get("expires_in").toString();
                    resultMap.put("curr_time", System.currentTimeMillis() / 1000 + "");
                    resultMap.put("access_token", accessToken);
                    resultMap.put("expires_in", acDuration);
                }
            } else {
                log.warn("获取的access_token结果为null");
            }
        } catch (Exception e) {
            log.error("getAccessToken error {}", e);
        }
        return resultMap.get("access_token");
    }

    /**
     * 发送微信模板消息
     * @param message
     */
    public void sendMessage(TemplateMessage message){
        String sendInfoUrl=sendContentUrl+getAccessToken();
        if (StringUtils.isEmpty(message.getUser())||StringUtils.isEmpty(message.getTemplateId())|| CollectionUtils.isEmpty(message.getData())){
            log.error("微信模板消息格式错误");
            return;
        }

        String post = HttpUtil.post(sendInfoUrl, message.toJsonStr());
        log.warn("SendWechatUtils wxResultStr {}", post);
    }

    public static void main(String[] args) {
        WxUtils wxUtils = new WxUtils("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential", "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=", "wx44dbe0c10d9468a0", "579000cf738dd93bb31d562fe596ceb2", "");
        //WxUtils wxUtils = new WxUtils("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential", "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=", "wx37ef1ac6d1cbf5e0", "aff627fd69e10c4b655d3df55bf5d499", "");
        TemplateMessage templateMessage = new TemplateMessage("ofu3st7u7-OULvV9MVPWXp0iY9aA", "o2MftpbwVxUwwvINJdI-71nUxEILjHNkI3T1ax98Jmg");
        //TemplateMessage templateMessage = new TemplateMessage("ox3rr6o8Uu4oKSmIulH0mzUW_zOU", "zbRIqPDtTl-NyO_jwCbbt_-H0HpTlZf6sckrjbwR-R0");
        templateMessage.addData("first","test",null);
        templateMessage.addData("keyword1","test",null);
        templateMessage.addData("keyword2","test",null);
        templateMessage.addData("keyword3","调用接口: 123213\n 告警类型:123123\n",null);
        templateMessage.addData("remark","调用接口: 123213\n 告警类型:123123\n",null);
        wxUtils.sendMessage(templateMessage);
        System.out.println(templateMessage.toJsonStr());

    }

}

